package io.kljf.boot.modules.security.controller;

import io.kljf.boot.common.constant.CommonConstant;
import io.kljf.boot.common.utils.JwtUtil;
import io.kljf.boot.common.utils.RedisUtil;
import io.kljf.boot.common.utils.Result;
import io.kljf.boot.modules.security.dto.LoginDTO;
import io.kljf.boot.modules.security.service.IShiroService;
import io.kljf.boot.modules.sys.entity.UserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author katherine
 * @version 2020-12-04
 **/
@Api(tags = "登陆接口")
@RestController
public class LoginController {

    @Autowired
    private IShiroService shiroService;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    @ApiOperation(value="登录")
    private Result<String>login(HttpServletRequest request, @RequestBody LoginDTO login) throws Exception {
        UserEntity user = shiroService.getUserByUserName(login.getUsername());
        String token = "";
        if(user == null){
            throw new Exception("username or password is wrong");
        }else if(!user.getPassword().equals(login.getPassword())){
            throw new Exception("username or password is wrong");
        }else{
            String syspassword = user.getPassword();
            String username = user.getUsername();
            // 生成token
            token = JwtUtil.generateToken(username, syspassword);
            // 设置token缓存有效时间
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRES_IN*2 / 1000);

        }
        return new Result<String>().ok(token);
    }

    @GetMapping("/user/info")
    @ApiOperation(value="用户信息")
    private Result userInfo(){
        return new Result().ok("success");
    }
}
